package com.sk.weichat.ui.message.search;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.adapter.SearchChatRecodeAdapter;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.broadcast.MsgBroadcast;
import com.sk.weichat.db.dao.ChatMessageDao;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.base.EditBaseActivity;
import com.sk.weichat.ui.message.ChatActivity;
import com.sk.weichat.ui.message.MucChatActivity;
import com.sk.weichat.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * 搜索聊天记录
 */
public class SearchChatRecordActivity extends EditBaseActivity implements View.OnClickListener {

    private LinearLayout ll_layout_search_empty;

    private ImageView iv_title_left;
    private EditText et_search_user;
    private ImageView iv_clear_user;
    private TextView tv_finish_search_user;

    //聊天记录
    private LinearLayout ll_chat_record;
    private RecyclerView recy_chat_record;
    private List<Friend> mChatRecordList = new ArrayList<>();//聊天记录列表
    private SearchChatRecodeAdapter mChatRecordAdapter;
    private String mLoginUserId;

    private String search_more;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_chat_record);
        getSupportActionBar().hide();
        mLoginUserId = coreManager.getSelf().getUserId();
        initView();
        initChatRecodeView();
    }

    private void initView() {
        ll_layout_search_empty = findViewById(R.id.ll_layout_search_empty);

        iv_title_left = findViewById(R.id.iv_title_left);
        et_search_user = findViewById(R.id.et_search_user);
        iv_clear_user = findViewById(R.id.iv_clear_user);
        tv_finish_search_user = findViewById(R.id.tv_finish_search_user);

        iv_title_left.setOnClickListener(this);
        iv_clear_user.setOnClickListener(this);
        tv_finish_search_user.setOnClickListener(this);
        //弹出键盘输入
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        et_search_user.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s == null || s.length() == 0) {
                    iv_clear_user.setVisibility(View.INVISIBLE);
                    ll_layout_search_empty.setVisibility(View.GONE);
                    //清除聊天记录列表
                    mChatRecordList.clear();
                    mChatRecordAdapter.notifyDataSetChanged();
                    ll_chat_record.setVisibility(View.GONE);
                    return;
                }
                iv_clear_user.setVisibility(View.VISIBLE);
                mChatRecordAdapter.setKeyword(s.toString());

                SearchChatRecode();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        et_search_user.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    if (TextUtils.isEmpty(et_search_user.getText().toString())) {
                        ToastUtil.showToast(SearchChatRecordActivity.this, "请输入搜索内容");
                        return true;
                    }

                    SearchChatRecode();
                    return true;
                }
                return false;
            }
        });

        /*延迟加载 等待控件初始化*/
        new Handler().postDelayed(new Runnable() {
            public void run() {
                search_more = getIntent().getStringExtra("search_more");
                if (!TextUtils.isEmpty(search_more)) {
                    et_search_user.setText(search_more);
                    et_search_user.setSelection(search_more.length());
                    SearchChatRecode();
                }
            }
        }, 50);

    }


    /**
     * 初始化 聊天记录
     */
    private void initChatRecodeView() {
        //聊天记录
        ll_chat_record = findViewById(R.id.ll_chat_record);
        recy_chat_record = findViewById(R.id.recy_chat_record);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recy_chat_record.setLayoutManager(manager);
        mChatRecordAdapter = new SearchChatRecodeAdapter(mChatRecordList, true);
        mChatRecordAdapter.setHasStableIds(true);
        recy_chat_record.setNestedScrollingEnabled(true);
        recy_chat_record.setAdapter(mChatRecordAdapter);
        //禁止RecyclerView的默认动画
        ((SimpleItemAnimator) recy_chat_record.getItemAnimator()).setSupportsChangeAnimations(false);
        mChatRecordAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                Friend friend = mChatRecordList.get(position);
                if (friend.getRoomFlag() == 0) {//单聊记录
                    Intent intent = null;
                    if (friend.getContextNum() > 1) {
                        intent = new Intent(SearchChatRecordActivity.this, MoreChatRecordActivity.class);
                        intent.putExtra(ChatActivity.FRIEND, friend);
                        intent.putExtra("content", et_search_user.getText().toString());
                    } else {
                        intent = new Intent(SearchChatRecordActivity.this, ChatActivity.class);
                        intent.putExtra(ChatActivity.FRIEND, friend);
                        intent.putExtra("isserch", true);
                        intent.putExtra("jilu_id", friend.getChatRecordTimeOut());
                    }
                    startActivity(intent);
                } else {//群聊记录
                    Intent intent = null;
                    if (friend.getContextNum() > 1) {
                        intent = new Intent(SearchChatRecordActivity.this, MoreChatRecordActivity.class);
                        intent.putExtra(ChatActivity.FRIEND, friend);
                        intent.putExtra("content", et_search_user.getText().toString());
                    } else {
                        intent = new Intent(SearchChatRecordActivity.this, MucChatActivity.class);
                        intent.putExtra(AppConstant.EXTRA_USER_ID, friend.getUserId());
                        intent.putExtra(AppConstant.EXTRA_NICK_NAME, friend.getNickName());
                        intent.putExtra(AppConstant.EXTRA_IS_GROUP_CHAT, true);
                        if (friend.getUnReadNum() > 0) {// 如该群组未读消息数量大于1, 刷新MessageFragment
                            MsgBroadcast.broadcastMsgNumReset(SearchChatRecordActivity.this);
                            MsgBroadcast.broadcastMsgUiUpdate(SearchChatRecordActivity.this);
                        }
                    }
                    startActivity(intent);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v == iv_title_left) {
            finish();
        } else if (v == tv_finish_search_user) {
            EventBus.getDefault().post("cancle");
            finish();
        } else if (v == iv_clear_user) {
            et_search_user.setText("");
        }
    }

    /**
     * 搜索聊天记录
     */
    private void SearchChatRecode() {
        List<Friend> chat_datas = ChatMessageDao.getInstance().queryAllChatMessageByContent(mLoginUserId, et_search_user.getText().toString());//查找聊天记录
        if (chat_datas != null && chat_datas.size() > 0) {
            if (mChatRecordList.size() > 0) {
                mChatRecordList.clear();
            }
            for (Friend friend : chat_datas) {
                mChatRecordList.add(friend);
            }
            mChatRecordAdapter.notifyDataSetChanged();
            ll_chat_record.setVisibility(View.VISIBLE);
        } else {
            if (mChatRecordList.size() > 0) {
                mChatRecordList.clear();
                mChatRecordAdapter.notifyDataSetChanged();
            }
            ll_chat_record.setVisibility(View.GONE);
        }

        /*判断列表大小 0则页面显示搜索为空页面*/
        if (mChatRecordList.size() == 0) {
            ll_layout_search_empty.setVisibility(View.VISIBLE);
        } else {
            ll_layout_search_empty.setVisibility(View.GONE);
        }
    }
}
